#include "pitd.h"
#include <board.h>
#include <pit/pit.h>
#include <aic/aic.h>

// The pit accuracy will be (1 / PIT_ACCURACY) seconds
#define PIT_ACCURACY 1000000

volatile unsigned int timestamp = 0;

isr current_callback;

static void handler()
{
    if (PIT_GetStatus() & AT91C_PITC_PITS)
        timestamp += (PIT_GetPIVR() >> 20);

    current_callback();
}

void PITD_Configure(isr callback, unsigned int period, int is_prioritary)
{
    // PITD_Stop();

    current_callback = callback;

    PIT_Init(period, BOARD_MCK / PIT_ACCURACY);

    AIC_DisableIT(AT91C_ID_SYS);
    AIC_ConfigureIT(AT91C_ID_SYS,
            is_prioritary ? AT91C_AIC_PRIOR_HIGHEST : AT91C_AIC_PRIOR_LOWEST,
            handler);
    AIC_EnableIT(AT91C_ID_SYS);
}
